package com.xhs.zdl.demo.gridViewDemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;

import com.xhs.zdl.demo.MyUtils;
import com.xhs.zdl.demo.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GridViewDemo extends AppCompatActivity {

    private GridView gridView;
    private ArrayList<Map<String, Object>> data_list;
    private SimpleAdapter simpleAdapter;

    private int[] icon = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher,
            R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
    private String[] icon_name = {"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_view_demo);

        findView();
        initView();
    }

    private void initView() {
        data_list = new ArrayList<>();
        //获取数据
        getData();
        //新建适配器
        String[] from = {"img", "name"};
        int[] to = {R.id.gridView_img, R.id.gridView_name};
        simpleAdapter = new SimpleAdapter(this, data_list, R.layout.gridview_item, from, to);
        //配置适配器
        gridView.setAdapter(simpleAdapter);
        //绑定监听器
        gridView.setOnItemClickListener(onItemClickListener);
    }

    /**
     * 得到数据源
     * @return
     */
    private List<Map<String, Object>> getData() {
        Map<String, Object> map;
        for (int i = 0; i < icon.length; i++) {
            map = new HashMap<>();
            map.put("img", icon[i]);
            map.put("name", icon_name[i]);
            data_list.add(map);
        }

        return data_list;
    }

    /**
     * 拿到控件
     */
    private void findView() {
        gridView = (GridView) findViewById(R.id.gridView);
    }

    /**
     * gridView监听器
     */
    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            MyUtils.Toast(GridViewDemo.this, "点击了：" + icon_name[i]);
        }
    };
}
